<template>
  <div class="order-management">
    <h2 class="page-title">订单管理</h2>
    
    <!-- 搜索和过滤 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="queryParams" class="filter-form">
        <el-form-item label="订单号">
          <el-input v-model="queryParams.orderNo" placeholder="请输入订单号" clearable></el-input>
        </el-form-item>
        <el-form-item label="下单时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            @change="handleDateRangeChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 订单列表 -->
    <el-card class="table-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部订单" name="all"></el-tab-pane>
        <el-tab-pane label="待接单" name="pending"></el-tab-pane>
        <el-tab-pane label="配送中" name="delivering"></el-tab-pane>
        <el-tab-pane label="已完成" name="completed"></el-tab-pane>
        <el-tab-pane label="已取消" name="cancelled"></el-tab-pane>
      </el-tabs>
      
      <el-table
        :data="orderList"
        border
        stripe
        v-loading="loading">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column prop="userId" label="用户ID" width="100"></el-table-column>
        <el-table-column prop="totalAmount" label="订单金额" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount ? scope.row.totalAmount.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="实付金额" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.actualAmount ? scope.row.actualAmount.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template slot-scope="scope">
            {{ getPaymentMethodText(scope.row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="订单状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180">
          <template slot-scope="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleViewDetail(scope.row)">查看</el-button>
            <el-button 
              v-if="scope.row.status === 1" 
              type="text" 
              size="small" 
              @click="handleAcceptOrder(scope.row)">接单</el-button>
            <el-button 
              v-if="scope.row.status === 2" 
              type="text" 
              size="small" 
              @click="handleStartDelivery(scope.row)">配送</el-button>
            <el-button 
              v-if="scope.row.status === 3" 
              type="text" 
              size="small" 
              @click="handleDeliveryComplete(scope.row)">送达</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          :current-page="queryParams.page"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      :visible.sync="orderDetailVisible"
      width="800px">
      <div v-if="currentOrder" class="order-detail">
        <!-- 订单基本信息 -->
        <div class="detail-section">
          <div class="section-title">基本信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单ID">{{ currentOrder.id }}</el-descriptions-item>
            <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="用户ID">{{ currentOrder.userId }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getOrderStatusType(currentOrder.status)">
                {{ getOrderStatusText(currentOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ formatTime(currentOrder.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="支付时间">{{ currentOrder.status >= 1 && currentOrder.status !== 5 ? formatTime(currentOrder.paymentTime) : '未支付' }}</el-descriptions-item>
            <el-descriptions-item label="配送时间">{{ currentOrder.status >= 3 ? formatTime(currentOrder.deliveryTime) : '未配送' }}</el-descriptions-item>
            <el-descriptions-item label="完成时间">{{ currentOrder.status >= 4 ? formatTime(currentOrder.completeTime) : '未完成' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 金额信息 -->
        <div class="detail-section">
          <div class="section-title">金额信息</div>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="商品总额">¥{{ currentOrder.totalAmount ? currentOrder.totalAmount.toFixed(2) : '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="配送费">¥{{ currentOrder.deliveryFee ? currentOrder.deliveryFee.toFixed(2) : '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="优惠金额">¥{{ currentOrder.discountAmount ? currentOrder.discountAmount.toFixed(2) : '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="实付金额">¥{{ currentOrder.actualAmount ? currentOrder.actualAmount.toFixed(2) : '0.00' }}</el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ getPaymentMethodText(currentOrder.paymentMethod) }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">
              <el-tag :type="currentOrder.status >= 1 && currentOrder.status !== 5 ? 'success' : 'danger'">
                {{ currentOrder.status >= 1 && currentOrder.status !== 5 ? '已支付' : '未支付' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 收货信息 -->
        <div class="detail-section">
          <div class="section-title">收货信息</div>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="收货人">{{ currentOrder.receiverName }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentOrder.receiverPhone }}</el-descriptions-item>
            <el-descriptions-item label="收货地址">{{ currentOrder.deliveryAddress }}</el-descriptions-item>
            <el-descriptions-item label="订单备注">{{ currentOrder.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <!-- 商品列表 -->
        <div class="detail-section">
          <div class="section-title">商品列表</div>
          <el-table
            :data="currentOrder.items || []"
            border
            stripe>
            <el-table-column prop="foodId" label="商品ID" width="80"></el-table-column>
            <el-table-column prop="foodName" label="商品名称" width="200"></el-table-column>
            <el-table-column prop="price" label="单价" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.price ? scope.row.price.toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="80"></el-table-column>
            <el-table-column prop="subtotal" label="小计" width="100">
              <template slot-scope="scope">
                ¥{{ scope.row.subtotal ? scope.row.subtotal.toFixed(2) : (scope.row.price * scope.row.quantity).toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注"></el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDetailVisible = false">关闭</el-button>
        <el-button 
          v-if="currentOrder && currentOrder.status === 1"
          type="primary" 
          @click="handleAcceptOrder(currentOrder)">接单</el-button>
        <el-button 
          v-if="currentOrder && currentOrder.status === 2"
          type="primary" 
          @click="handleStartDelivery(currentOrder)">开始配送</el-button>
        <el-button 
          v-if="currentOrder && currentOrder.status === 3"
          type="success" 
          @click="handleDeliveryComplete(currentOrder)">标记送达</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { updateOrderStatus } from '@/api/order'

export default {
  name: 'MerchantOrderManagement',
  data() {
    return {
      // 查询参数
      queryParams: {
        page: 1,
        size: 10,
        merchantId: null,
        orderNo: '',
        startTime: '',
        endTime: ''
      },
      
      // 日期范围
      dateRange: [],
      
      // 当前激活的标签页
      activeTab: 'all',
      
      // 订单列表
      orderList: [],
      
      // 总记录数
      total: 0,
      
      // 加载状态
      loading: false,
      
      // 当前查看的订单
      currentOrder: null,
      
      // 订单详情对话框可见性
      orderDetailVisible: false
    }
  },
  created() {
    this.getMerchantId()
  },
  methods: {
    // 格式化时间
    formatTime(time) {
      if (!time) return '暂无';
      // 如果已经是格式化过的时间字符串，直接返回
      if (typeof time === 'string' && time.includes('-')) {
        return time;
      }
      // 如果是时间戳，则格式化
      if (typeof time === 'number') {
        const date = new Date(time);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      }
      return '暂无';
    },
    
    // 获取商家ID
    getMerchantId() {
      const userId = this.$store.state.user.id
      axios.get(`/api/merchants/user/${userId}`)
        .then(response => {
          if (response.code === 200) {
            this.queryParams.merchantId = response.data.id
            this.fetchOrderList()
          } else {
            this.$message.error(response.message || '获取商家信息失败')
          }
        })
        .catch(error => {
          console.error('获取商家信息失败', error)
          this.$message.error('获取商家信息失败')
        })
    },
    
    // 获取订单列表
    fetchOrderList() {
      this.loading = true
      
      // 构建查询参数
      const params = { ...this.queryParams }
      
      // 根据标签页设置状态
      if (this.activeTab === 'pending') {
        params.status = 1 // 待接单
      } else if (this.activeTab === 'delivering') {
        params.status = 3 // 配送中
      } else if (this.activeTab === 'completed') {
        params.status = 4 // 已完成
      } else if (this.activeTab === 'cancelled') {
        params.status = 5 // 已取消
      }
      
      axios.get(`/api/orders/merchant/${this.queryParams.merchantId}`, { params })
        .then(response => {
          if (response.code === 200) {
            this.orderList = response.data
            this.total = response.total
          } else {
            this.$message.error(response.message || '获取订单列表失败')
          }
          this.loading = false
        })
        .catch(error => {
          console.error('获取订单列表失败', error)
          this.$message.error('获取订单列表失败')
          this.loading = false
        })
    },
    
    // 处理日期范围变化
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.startTime = val[0]
        this.queryParams.endTime = val[1]
      } else {
        this.queryParams.startTime = ''
        this.queryParams.endTime = ''
      }
    },
    
    // 处理查询
    handleQuery() {
      this.queryParams.page = 1
      this.fetchOrderList()
    },
    
    // 重置查询
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        page: 1,
        size: 10,
        merchantId: this.queryParams.merchantId,
        orderNo: '',
        startTime: '',
        endTime: ''
      }
      this.fetchOrderList()
    },
    
    // 处理标签页点击
    handleTabClick() {
      this.queryParams.page = 1
      this.fetchOrderList()
    },
    
    // 处理每页大小变化
    handleSizeChange(size) {
      this.queryParams.size = size
      this.fetchOrderList()
    },
    
    // 处理页码变化
    handleCurrentChange(page) {
      this.queryParams.page = page
      this.fetchOrderList()
    },
    
    // 查看订单详情
    handleViewDetail(order) {
      // 获取订单详情
      axios.get(`/api/orders/${order.id}`)
        .then(response => {
          if (response.code === 200) {
            this.currentOrder = response.data
            
            // 获取订单商品详情
            axios.get(`/api/order-details/order/${order.id}`)
              .then(itemsResponse => {
                if (itemsResponse.code === 200) {
                  this.currentOrder.items = itemsResponse.data
                  this.orderDetailVisible = true
                }
              })
              .catch(error => {
                console.error('获取订单商品详情失败', error)
                this.$message.error('获取订单商品详情失败')
              })
          } else {
            this.$message.error(response.message || '获取订单详情失败')
          }
        })
        .catch(error => {
          console.error('获取订单详情失败', error)
          this.$message.error('获取订单详情失败')
        })
    },
    
    // 接受订单
    handleAcceptOrder(order) {
      this.$confirm('确认接受该订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(order.id, 2) // 更新为备餐中状态
          .then(response => {
            if (response.code === 200) {
              this.$message.success('订单已接受，进入备餐状态')
              this.fetchOrderList() // 刷新列表
              
              if (this.orderDetailVisible && this.currentOrder) {
                this.handleViewDetail(order) // 刷新详情
              }
            } else {
              this.$message.error(response.message || '接单失败')
            }
          })
          .catch(error => {
            console.error('接单失败', error)
            this.$message.error('接单失败')
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 完成配送
    handleDeliveryComplete(order) {
      this.$confirm('确认订单已送达？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(order.id, 4) // 更新为已完成状态
          .then(response => {
            if (response.code === 200) {
              this.$message.success('订单已完成')
              this.fetchOrderList() // 刷新列表
              
              if (this.orderDetailVisible && this.currentOrder) {
                this.handleViewDetail(order) // 刷新详情
              }
            } else {
              this.$message.error(response.message || '操作失败')
            }
          })
          .catch(error => {
            console.error('完成订单失败', error)
            this.$message.error('操作失败')
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 开始配送
    handleStartDelivery(order) {
      this.$confirm('确认开始配送该订单？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateOrderStatus(order.id, 3) // 更新为配送中状态
          .then(response => {
            if (response.code === 200) {
              this.$message.success('订单已开始配送')
              this.fetchOrderList() // 刷新列表
              
              if (this.orderDetailVisible && this.currentOrder) {
                this.handleViewDetail(order) // 刷新详情
              }
            } else {
              this.$message.error(response.message || '操作失败')
            }
          })
          .catch(error => {
            console.error('开始配送失败', error)
            this.$message.error('操作失败')
          })
      }).catch(() => {
        // 取消操作
      })
    },
    
    // 获取订单状态类型（用于标签颜色）
    getOrderStatusType(status) {
      const types = {
        0: 'info',     // 待付款
        1: 'warning',  // 待接单
        2: 'primary',  // 备餐中
        3: 'success',  // 配送中
        4: 'info',     // 已完成
        5: 'danger'    // 已取消
      }
      return types[status] || 'info'
    },
    
    // 获取订单状态文本
    getOrderStatusText(status) {
      const texts = {
        0: '待付款',
        1: '待接单',
        2: '备餐中',
        3: '配送中',
        4: '已完成',
        5: '已取消'
      }
      return texts[status] || '未知状态'
    },
    
    // 获取支付方式文本
    getPaymentMethodText(method) {
      const texts = {
        1: '微信支付',
        2: '支付宝',
        3: '校园卡'
      }
      return texts[method] || '未知方式'
    }
  }
}
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.page-title {
  margin-bottom: 20px;
  font-size: 24px;
  font-weight: bold;
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-section {
  margin-bottom: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}
</style> 